package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.R;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.model.ChatMessage;
import com.google.android.material.imageview.ShapeableImageView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 聊天消息RecyclerView适配器，用于在聊天界面展示消息列表
 * 支持显示自己和他人发送的消息，并根据时间间隔智能显示时间戳
 */
public class ChatMessageAdapter extends RecyclerView.Adapter<ChatMessageAdapter.ChatViewHolder> {

    // 聊天消息数据集
    private List<ChatMessage> chatMessages;
    // 上下文引用，用于加载布局资源
    private Context context;

    /**
     * 构造函数，初始化适配器
     * @param context 上下文对象
     * @param messages 聊天消息列表
     */
    public ChatMessageAdapter(Context context, List<ChatMessage> messages) {
        this.context = context;
        this.chatMessages = messages;
    }

    /**
     * 创建ViewHolder实例，加载消息列表项布局
     * @param parent 父视图组
     * @param viewType 视图类型
     * @return ChatViewHolder实例
     */
    @NonNull
    @Override
    public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_item_chat, parent, false);
        return new ChatViewHolder(view);
    }

    /**
     * 绑定ViewHolder，设置消息内容、时间戳和发送方信息
     * @param holder 视图持有者
     * @param position 当前位置
     */
    @Override
    public void onBindViewHolder(@NonNull ChatViewHolder holder, int position) {
        ChatMessage message = chatMessages.get(position);

        // 智能时间显示逻辑：
        // 1. 第一条消息总是显示时间
        // 2. 与上一条消息间隔超过1分钟时显示时间
        long currentTimestamp = message.getTimestamp();
        long prevTimestamp = position > 0 ? chatMessages.get(position - 1).getTimestamp() : 0;
        boolean showTime = position == 0 || (currentTimestamp - prevTimestamp) > 60 * 1000;

        if (showTime) {
            // 显示时间戳并格式化
            holder.messageTimeTextView.setVisibility(View.VISIBLE);
            holder.messageTimeTextView.setText(formatTime(currentTimestamp));
        } else {
            // 隐藏时间戳以保持界面简洁
            holder.messageTimeTextView.setVisibility(View.GONE);
        }


        // 根据消息归属显示不同样式
        if (message.isOwnMessage()) {
            // 显示自己发送的消息样式
            holder.ownMessageLayout.setVisibility(View.VISIBLE);
            holder.otherMessageLayout.setVisibility(View.GONE);
            holder.ownMessageTextView.setText(message.getMessage());
            holder.ownAvatarImage.setVisibility(View.VISIBLE);
            holder.otherAvatarImage.setVisibility(View.GONE);
            holder.ownUserNameTextView.setText(message.getUserName());
            holder.ownUserNameTextView.setVisibility(View.VISIBLE);
            holder.otherUserNameTextView.setVisibility(View.GONE);
        } else {
            // 显示他人发送的消息样式
            holder.otherMessageLayout.setVisibility(View.VISIBLE);
            holder.ownMessageLayout.setVisibility(View.GONE);
            holder.otherMessageTextView.setText(message.getMessage());
            holder.ownAvatarImage.setVisibility(View.GONE);
            holder.otherAvatarImage.setVisibility(View.VISIBLE);
            holder.otherUserNameTextView.setText(message.getUserName());
            holder.ownUserNameTextView.setVisibility(View.GONE);
            holder.otherUserNameTextView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取消息数量
     * @return 消息列表大小
     */
    @Override
    public int getItemCount() {
        return chatMessages.size();
    }

    /**
     * 根据消息时间戳智能格式化时间显示
     * - 今年以前：显示完整日期时间 yyyy-MM-dd HH:mm
     * - 今年内但非本月：显示月日时间 MM-dd HH:mm
     * - 本月内但非今天：显示日时间 dd HH:mm
     * - 今天：只显示时间 HH:mm
     * @param timestamp 时间戳（毫秒）
     * @return 格式化后的时间字符串
     */
    private String formatTime(long timestamp) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp);

        Calendar now = Calendar.getInstance();

        SimpleDateFormat sdf;
        if (calendar.get(Calendar.YEAR) < now.get(Calendar.YEAR)) {
            // 显示完整日期和时间
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        } else if (calendar.get(Calendar.MONTH) < now.get(Calendar.MONTH)) {
            // 显示月、日和时间
            sdf = new SimpleDateFormat("MM-dd HH:mm", Locale.getDefault());
        } else if (calendar.get(Calendar.DAY_OF_MONTH) < now.get(Calendar.DAY_OF_MONTH)) {
            // 显示日和时间
            sdf = new SimpleDateFormat("dd HH:mm", Locale.getDefault());
        } else {
            // 只显示时间
            sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
        }

        return sdf.format(new Date(timestamp));
    }

    /**
     * 聊天消息ViewHolder，缓存消息视图组件引用
     */
    public static class ChatViewHolder extends RecyclerView.ViewHolder {
        // 时间戳文本视图
        TextView messageTimeTextView;
        // 他人消息布局容器
        LinearLayout otherMessageLayout;
        // 自己消息布局容器
        LinearLayout ownMessageLayout;
        // 他人消息内容文本视图
        TextView otherMessageTextView;
        // 自己消息内容文本视图
        TextView ownMessageTextView;
        TextView ownUserNameTextView;
        TextView otherUserNameTextView;

        ShapeableImageView ownAvatarImage;
        ShapeableImageView otherAvatarImage;

        /**
         * 构造函数，初始化ViewHolder中的视图组件
         * @param itemView 列表项视图
         */
        public ChatViewHolder(@NonNull View itemView) {
            super(itemView);
            messageTimeTextView = itemView.findViewById(R.id.messageTimeTextView);
            otherMessageLayout = itemView.findViewById(R.id.otherMessageLayout);
            ownMessageLayout = itemView.findViewById(R.id.ownMessageLayout);
            otherMessageTextView = itemView.findViewById(R.id.otherMessageTextView);
            ownMessageTextView = itemView.findViewById(R.id.ownMessageTextView);
            ownAvatarImage = itemView.findViewById(R.id.ownAvatarImage);
            otherAvatarImage = itemView.findViewById(R.id.otherAvatarImage);
            ownUserNameTextView = itemView.findViewById(R.id.ownUserNameTextView);
            otherUserNameTextView = itemView.findViewById(R.id.otherUserNameTextView);
        }
    }
}